package com.opencms.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.opencms.bean.SysUser;
import com.opencms.bean.SysUserRole;
import com.opencms.dao.SysUserMapper;
import com.opencms.dao.SysUserRoleMapper;
import com.opencms.dao.base.MapperSupport;
import com.opencms.service.SysUserService;
import com.opencms.service.base.impl.ServiceSupportImpl;

@Service
public class SysUserServiceImpl extends ServiceSupportImpl<SysUser> implements SysUserService {
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Override
	public MapperSupport<SysUser> getMapperSupport() {
		return sysUserMapper;
	}

	@Override
	public void addOrUpdate(SysUser sysUser, String roleIds) {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("sysUserId",sysUser.getId());
		sysUserRoleMapper.deleteByParams(params);
		if (StringUtils.isNotBlank(roleIds)) {
			String[] ids=StringUtils.split(roleIds,",");
			for (int i = 0; i < ids.length; i++) {
				SysUserRole sysUserRole = new SysUserRole();
				sysUserRole.setSysUserId(sysUser.getId());
				sysUserRole.setRoleId(Integer.valueOf(ids[i]));
				sysUserRoleMapper.insertSelective(sysUserRole);
			}
		}
		if(sysUser.getId()!=null){
			sysUserMapper.updateByPrimaryKeySelective(sysUser);
		}else{
			sysUserMapper.insertSelective(sysUser);
		}
	}

}
